package jdbc.preparestatement_;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * @author DCSGO
 * @version 1.0
 * PrepareStatement
 */
@SuppressWarnings({"all"})
public class PrepareStatement_ {
    //预处理好处
    //1.不再使用+拼接sql语句，减少语法错误
    //2.有效的解决了sql注入问题!
    //3.大大减少了编译次数,效率较高
    public static void main(String[] args) throws Exception{
        //演示用户登录
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入管理员名：");
        String admin_name = scanner.nextLine();// 读取空格
        System.out.println("请输入密码：");
        String admin_pwd = scanner.nextLine();
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String Driver = properties.getProperty("Driver");
        //1.注册驱动
        Class.forName(Driver);
        //2.获取连接
        Connection connection = DriverManager.getConnection(url, user, password);
        //3.获取 PrepareStatement
        String sql = "select * from admin where `name` = ? and pwd = ?";//? 为占位符
        PreparedStatement prepareStatement = connection.prepareStatement(sql);//在获取时需要填写一个 sql 语句
        //4.执行查询
        prepareStatement.setString(1,admin_name);//设置sql语句中第几个?的值为啥
        prepareStatement.setString(2,admin_pwd);
        ResultSet resultSet = prepareStatement.executeQuery();
        if(resultSet.next()){//查询到至少一条记录
            System.out.println("登录成功！");
        }else{
            System.out.println("登录失败！");
        }
        /*解决了注入问题
         * 请输入管理员名：
         * 1' or
         * 请输入密码：
         * OR '1' = '1
         * 登录失败！
         *
         * 进程已结束，退出代码为 0
         */

        resultSet.close();
        prepareStatement.close();
        connection.close();
    }
}
